<template>
<!-- 账户批量绑定 -->
<div class="student_bulk_order">
  <el-form :inline="true" :model="elform" class="demo-form-inline" size="mini">
    <el-form-item>
      <el-button type="primary" size="mini" icon="el-icon-download" @click="thetemplate()">execl模板下载</el-button>
    </el-form-item>
    <el-form-item style="paddingLeft:20px">
      <el-upload class="upload-demo" action :on-change="handleChange" :on-exceed="handleExceed" :on-remove="handleRemove" :file-list="fileListUpload" :limit="limitUpload" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" :auto-upload="false">
        <el-button type="primary" @click="handleclickto()" icon="el-icon-upload2">浏览</el-button>
      </el-upload>
    </el-form-item>
    <el-form-item style="paddingLeft:20px">
      <el-button type="primary" size="mini" @click="packgebatchto(tableChecked)">批量绑定</el-button>
    </el-form-item>
    <el-form-item style="paddingLeft:20px">
      <el-button type="primary" @click="exportexecl()">导出</el-button>
    </el-form-item>
  </el-form>
  <!-- 导入表格 -->
  <el-table v-if="tochannel" id="export-table" :data="changestudentlist" :stripe="true" style="width:100%" border="border" :header-cell-style="headFirst" highlight-current-row @selection-change="handleSelectionChange" :show-overflow-tooltip="true" key="table1" v-loading="importLoad" height="70vh" ref="importTable">
    <el-table-column label="是否选中" prop="isCheck" align="center" width="55">
      <template slot="header" slot-scope="scope">
        <el-checkbox :value="isSelectAll" @change="CheckSelectAll" :disabled="isError" />
      </template>
      <template slot-scope="scope">
        <el-checkbox :value="scope.row.isCheck" @change="(isCheck) =>CheckSelect(isCheck,scope.row)" :disabled="isError" />
      </template>
    </el-table-column>
    <!-- <el-table-column align="center" type="selection" width="55"></el-table-column> -->
    <el-table-column prop="errorStr" label="绑定失败原因" v-if="isError"></el-table-column>
    <el-table-column prop="departmentName" label="部门名称"></el-table-column>
    <el-table-column prop="userName" label="学生名称"></el-table-column>
    <el-table-column prop="loginPhone" label="绑定家长号码"></el-table-column>
  </el-table>
  <div class="page">
    <el-pagination @size-change="handleSizeChangeY" @current-change="handleCurrentChangepageY" :current-page="pageY" :page-sizes="[20,40, 80,120]" :page-size="pageSizeY" layout="total, sizes, prev, pager, next, jumper" :total="totalY"></el-pagination>
  </div>

</div>
</template>

<script>
export default {
  data() {
    return {
      // 导入表格等待
      importLoad: false,
      // 错误信息显示
      isError: false,
      // 是否全选
      isSelectAll: false,
      elform: {},
      limitUpload: 1,
      fileListUpload: [],
      studentlist: [],
      studentlistlen: 0,
      tableChecked: [],
      tochannel: true,
      changestudentlist: [],
      messageError: false,
      exportstudentlist: [],
      filename: "账户批量绑定情况",
      // 分页变量
      changestudentY: [],
      // 原始页数
      pageY: 1,
      // 每条个数
      pageSizeY: 20,
      // 总条数
      totalY: 0,
    };
  },
  created() {
    this.unitGuid = this.$store.state.user.changeschoolid;
  },
  methods: {
    // 模板下载
    thetemplate() {
      this.$http({
        url: this.$http.adornUrl("/api/v1/Student/poi-login-bind-user"),
        method: "post",
        data: this.$http.adornData({}),
        responseType: "blob",
      }).then(({
        data
      }) => {
        this.downloadFile(data);
      });
    },
    handleclickto() {

    },
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return;
      }
      const nowtime = this.getimeto();
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "账户批量绑定模板" + nowtime + ".xlsx");
      document.body.appendChild(link);
      link.click();
    },
    handleChange(file, fileList) {
      this.initList();
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.changestudentlist = [];
          this.messageError = false;
          this.tochannel = true;
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    handleExceed(file, fileList) {
      this.initList();
      fileList[0].name = file[0].name;
      this.fileTemps = file[0];
      if (this.fileTemps) {
        if (
          this.fileTemps.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemps.type == "application/vnd.ms-excel"
        ) {
          this.changestudentlist = [];
          this.messageError = false;
          this.tochannel = true;
          this.importfxx(this.fileTemps);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    handleRemove(file, fileList) {
      this.initList();
      this.changestudentlist = [];
      this.fileTemp = null;
    },
    handleSelectionChange(val) {
      this.tableChecked = val;
    },
    /**
     * 导入相关函数
     */
    // 数据初始化
    initList() {
      // 关闭加载
      this.importLoad = false;
      // 渲染表格初始化
      this.changestudentlist = [];
      // 表格中拿出的原始数据
      this.changestudentY = [];
      // 原始页数
      this.pageY = 1;
      // 每条个数
      this.pageSizeY = 20;
      // 总条数
      this.totalY = 0;
      // 原始的显示数据数
      this.showPageSizeY = 20;
      this.isSelectAll = false;
      this.isError = false;
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.changestudentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      );
    },
    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val;
      console.log(this.changestudentY)
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val;
      this.changestudentY.map((item) => {
        item.isCheck = val;
      });
    },
    // 导入数据处理
    getData() {
      let arr = [];
      this.changestudentY.map((item) => {
        if (item.isCheck) {
          arr.push(item);
        }
      });
      console.log(arr)
      return arr;
    },
    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },
    handleCurrentChangepageY(val) {
      this.pageY = val;
      this.getUserList(this.pageY, this.pageSizeY);
    },

    //导入函数
    importfxx(obj) {
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件
        // 读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((v) => {
            let obj = {};
            obj.departmentName = v["部门名称"];
            obj.userName = v["学生名称"];
            obj.loginPhone = v["绑定家长号码"];
            // obj.unitGuid = _this.unitGuid;
            arr.push(obj);
          });
          _this.studentlist = [...arr];
          let arrto = JSON.parse(JSON.stringify(_this.studentlist));
          // _this.studentlist = arrto
          // if (arrto.length > 0) {
          //   for (var i = 0; i < arrto.length; i++) {
          //     arrto[i].cardNumber = String(arrto[i].cardNumber);
          //   }
          // }
          arrto.map((item, index) => {
            item.isCheck = _this.isSelectAll;
            item.id = index;
          });
          console.log(arrto)
          _this.changestudentY = arrto;
          _this.totalY = arrto.length;
          _this.getUserList(_this.pageY, _this.pageSizeY);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    // 批量绑定
    packgebatchto() {
      if (this.importLoad) {
        this.$message({
          showClose: true,
          message: "正在批量绑定请勿重复操作",
          type: "warning",
          duration: "500"
        });
        return false;
      }
      let tableCheckedto = this.getData();
      //   let tableCheckedto = JSON.parse(JSON.stringify(this.tableChecked));
      if (tableCheckedto.length == 0) {
        this.$message({
          message: "没有绑定数据",
          type: "warning",
        });
        return false;
      }
      this.importLoad = true;
      this.$http({
        url: this.$http.adornUrl("/api/v1/Student/excel-login-bind-add"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            dataList: tableCheckedto,
            unitGuid: this.unitGuid
          },
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        this.importLoad = false;
        this.initList();
        if (data.messageCode == 500) {
          this.$message({
            message: "批量绑定失败",
            type: "warning",
          });
        }
        if (data.messageCode == 200) {
          if (data.messageContent) {
            this.changestudentY = data.messageContent;
            this.totalY = this.changestudentY.length;
            this.getUserList(this.pageY, this.pageSizeY);
            this.isError = true;
            this.$message({
              message: '部分数据批量绑定失败',
              type: "warning",
            });
            this.$nextTick(() => {
              this.$refs["importTable"].doLayout();
            });
          } else {
            this.$message({
              message: "批量绑定成功",
              type: "success",
            });
          }
        } else {
          this.$message({
            message: "批量绑定失败",
            type: "warning",
          });
        }
      });
    },
    //导出
    exportexecl() {
      if (
        this.changestudentlist.length != 0 &&
        this.changestudentlist[0].errorStr
      ) {
        this.export2Excel();
      } else {
        this.$message({
          message: "请批量绑定后再导出",
          type: "warning",
        });
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    //定义导出Excel表格事件
    export2Excel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        const multiHeader = [];
        const multiHeader2 = [];
        const merges = [];
        const {
          export_json_to_excel
        } = require("../../excel/Export2Excel");
        const tHeader = ["绑定失败原因", "部门名称", "学生名称", "绑定家长号码"];
        const filterVal = [
          "errorStr",
          "departmentName",
          "loginPhone",
          "userName"
        ];
        const list = this.changestudentY;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.student_bulk_order {

  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .page {
    padding-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  padding: 20px;

  .demo-form-inline,
  .demo-form-inline1 {
    height: 50px;
    width: 1234px;
    display: flex;

    /deep/.el-form-item__label {
      padding-right: 5px;
    }

    .el-form-item {
      margin-bottom: 0px;
    }

    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 250px;
    }
  }

  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;

    .searchmarigin {
      margin-left: 20px;
    }
  }

  .upload-demo {
    display: flex;
    align-items: center;

    /deep/.el-upload-list {
      //  margin-left: 60px;
    }

    /deep/.el-upload-list__item-name {
      margin-right: 22px;
    }
  }
}
</style>
